package com.blog.service.service;

import com.blog.check.result.Result;
import com.blog.dao.domain.PictureDO;
import com.blog.dao.query.PictureQuery;
import com.blog.exception.ServiceException;
import com.blog.form.PictureForm;
import com.blog.service.constant.SysPropertiesKeyConsts;
import com.blog.service.dto.PictureDTO;
import com.blog.until.BeanCopierUtil;
import com.blog.until.PrimaryKeyUtil;
import com.blog.until.RandomUtil;
import lombok.SneakyThrows;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Base64Utils;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

@Service
public class PictureService extends BaseService{

    Properties properties;
    {
        try {
            properties = getProperties(SYS_PROPERTIES_FILEPATH);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SneakyThrows
    private String photoSavePath(String location){
        String photoPath = properties.getProperty(SysPropertiesKeyConsts.PICTURE_PATH);
        Date time = getTime();
        if (StringUtils.isBlank(photoPath)){
            logger.error(SysPropertiesKeyConsts.ICON_PATH + "is blank");
            throw new Exception(SysPropertiesKeyConsts.ICON_PATH + "is blank");
        }
        String base64Prefix = StringUtils.substringBefore(location, ",");
        String suffix = getImageSuffix(base64Prefix);

        return photoPath + "/" + RandomUtil.getRandomCharAndNum(6) + "_"
                + DateFormatUtils.format(time, "yyyyMMddHHmmss") + suffix;

    }

    public Result list(PictureQuery pictureQuery){
        try{
            List<PictureDTO> pictureDTOList = new ArrayList<>();
            List<PictureDO> pictureDOList = pictureDAO.list(pictureQuery);
            if (pictureDOList.size() == 0) {
                return Result.success(pictureDTOList);
            }
            for (PictureDO pictureDO : pictureDOList){
                PictureDTO pictureDTO = getShowDTO(pictureDO);
                pictureDTOList.add(pictureDTO);
            }
            return Result.success(pictureDTOList);
        }catch (Exception e){
            throw new ServiceException(e);
        }
    }
    @SneakyThrows
    private PictureDTO getShowDTO(PictureDO pictureDO) {
        PictureDTO pictureDTO = new PictureDTO();
        pictureDTO.setId(pictureDO.getId());
        File file = new File(pictureDO.getPicturePath());
        if (file.exists()){
            byte[] bytes = FileUtils.readFileToByteArray(file);
            String icon = getImageBase64Prefix(file) + "," + Base64Utils.encodeToString(bytes);
            pictureDTO.setPicturePath(icon);
        }
        return pictureDTO;
    }

    @Transactional(rollbackFor = Exception.class)
    public Result get(String id){
        PictureDTO pictureDTO;
        PictureDO pictureDO = pictureDAO.get(id);
        pictureDTO = getShowDTO(pictureDO);
        return Result.success(pictureDTO);
    }

    @Transactional(rollbackFor = Exception.class)
    public Result save(PictureForm pictureForm){

        try {
            String destPath = photoSavePath(pictureForm.getPicturePath());
            PictureDO pictureDO = buildSavePicture(destPath);
            pictureDAO.save(pictureDO);

            String icon = StringUtils.substringAfter(pictureForm.getPicturePath(), ",");
            byte[] bytes = Base64Utils.decodeFromString(icon);

            FileUtils.writeByteArrayToFile(new File(destPath), bytes);
            return Result.success();
        }catch (Exception e){
            throw new ServiceException(e);
        }
    }
    @SneakyThrows
    private PictureDO buildSavePicture(String path) {
        PictureDO pictureDO = new PictureDO();
        pictureDO.setId(PrimaryKeyUtil.get());
        pictureDO.setPicturePath(path);
        return pictureDO;
    }

    @Transactional(rollbackFor = Exception.class)
    public Result update(String id,PictureForm pictureForm){

        try{
            String destPath = photoSavePath(pictureForm.getPicturePath());
            PictureDO pictureDO = buildUpdatePicture(destPath,id);
            pictureDAO.update(pictureDO);
            String icon = StringUtils.substringAfter(pictureForm.getPicturePath(), ",");
            byte[] bytes = Base64Utils.decodeFromString(icon);

            FileUtils.writeByteArrayToFile(new File(destPath), bytes);
            return Result.success();
        }catch (Exception e){
            throw new ServiceException(e);
        }

    }

    @SneakyThrows
    private PictureDO buildUpdatePicture(String destPath,String id) {
        PictureDO pictureDO = pictureDAO.get(id);
        PictureDO newPictureDO = BeanCopierUtil.create(pictureDO,PictureDO.class);
        newPictureDO.setPicturePath(destPath);
        return newPictureDO;
    }

    @Transactional(rollbackFor = Exception.class)
    public Result remove(String id){
        try{
            pictureDAO.remove(id);
            return Result.success();
        }catch (Exception e){
            throw new ServiceException(e);
        }
    }



}
